package cn.zcy.servlet.cookie;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebServlet("/servletDemo04")
public class ServletDemo04 extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=UTF-8");
        //通过响应对象写出提示信息
        resp.getWriter().write("欢迎访问本网站，您最后的访问时间是：<br>");
        //创建cookie对象，用于记录最后的访问时间
        Cookie cookie = new Cookie("time", String.valueOf(System.currentTimeMillis()));

        //设置在最大存活时间

        cookie.setMaxAge(3600);
        //将cookie添加到客户段
        resp.addCookie(cookie);

        //获取cookie

        Cookie[] cookies = req.getCookies();

        for (Cookie cookie1 : cookies) {
            if ("time".equals(cookie1.getName())) {
                String value = cookie1.getValue();
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                try {
//
                    String format = simpleDateFormat.format(new Date(Long.parseLong(value)));
                    System.out.println("format = " + format);
                    resp.getWriter().write(format);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }


    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
